package middleware

import (
	"strings"
	"time"
	"unicode"
	"unsafe"

	"github.com/json-iterator/go"
	"github.com/modern-go/reflect2"
)

// SetNamingStrategy rename struct fields uniformly
func SetNamingStrategy(translate func(reflect2.StructField, string) string) {
	jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate})
}

type namingStrategyExtension struct {
	jsoniter.DummyExtension
	translate func(reflect2.StructField, string) string
}

func (extension *namingStrategyExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {
	for _, binding := range structDescriptor.Fields {
		binding.ToNames = []string{extension.translate(binding.Field, binding.Field.Name())}
		binding.FromNames = []string{extension.translate(binding.Field, binding.Field.Name())}
	}
}

// LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world.
func LowerCaseWithUnderscores(field reflect2.StructField, name string) string {
	tag := field.Tag().Get("json")
	if tag != "" {
		li := strings.Split(tag, ",")
		if li[0] != "" {
			return li[0]
		}
	}
	newName := []rune{}
	for i, c := range name {
		if i == 0 {
			newName = append(newName, unicode.ToLower(c))
		} else {
			if unicode.IsUpper(c) {
				newName = append(newName, '_')
				newName = append(newName, unicode.ToLower(c))
			} else {
				newName = append(newName, c)
			}
		}
	}
	return string(newName)
}

// RegisterTimeAsFormatCodec encode/decode time since number of unit since epoch. the precision is the unit.
func RegisterTimeAsFormatCodec(format string) {
	jsoniter.RegisterTypeEncoder("time.Time", &timeAsFormatCodec{format})
	jsoniter.RegisterTypeDecoder("time.Time", &timeAsFormatCodec{format})
}

type timeAsFormatCodec struct {
	format string
}

func (codec *timeAsFormatCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
	t, err := time.Parse(codec.format, iter.ReadString())
	if err != nil {
		iter.ReportError("time.Decode", err.Error())
		return
	}
	*((*time.Time)(ptr)) = t
}

func (codec *timeAsFormatCodec) IsEmpty(ptr unsafe.Pointer) bool {
	ts := *((*time.Time)(ptr))
	return ts.UnixNano() == 0
}
func (codec *timeAsFormatCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
	ts := *((*time.Time)(ptr))
	ts.Format(codec.format)
	stream.WriteString(ts.Format(codec.format))
}
